﻿using System.Threading.Tasks;
using DailyPoetryX.Services;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;

namespace DailyPoetryX.ViewModels {
    public class InitializationPageViewModel : ViewModelBase {
        /******** 构造函数 ********/

        private IPoetryStorage poetryStorage;
        private IFavoriteStorage favoriteStorage;
        private IRootNavigationService rootNavigationService;

        public InitializationPageViewModel(IPoetryStorage poetryStorage,
            IFavoriteStorage favoriteStorage,
            IRootNavigationService rootNavigationService) {
            this.poetryStorage = poetryStorage;
            this.favoriteStorage = favoriteStorage;
            this.rootNavigationService = rootNavigationService;
        }

        /******** 绑定属性 ********/

        public string Status {
            get => _status;
            set => Set(nameof(Status), ref _status, value);
        }

        private string _status;

        /******** 绑定命令 ********/

        public RelayCommand PageAppearingCommand =>
            _pageAppearingCommand ?? (_pageAppearingCommand = new RelayCommand(
                async () => {
                    var run = false;

                    if (!pageLoaded) {
                        lock (pageLoadedLock) {
                            if (!pageLoaded) {
                                pageLoaded = true;
                                run = true;
                            }
                        }
                    }

                    if (!run) return;

                    if (!poetryStorage.Initialized()) {
                        Status = "正在初始化诗词数据库";
                        await poetryStorage.InitializeAsync();
                    }

                    if (!favoriteStorage.Initialized()) {
                        Status = "正在初始化收藏数据库";
                        await favoriteStorage.InitializeAsync();
                    }

                    Status = "所有初始化已完成";
                    await Task.Delay(1000);

                    await rootNavigationService.NavigateToAsync(
                        RootNavigationServiceConstants.AboutPage);
                }));

        private RelayCommand _pageAppearingCommand;

        /******** 私有变量 ********/

        private bool pageLoaded;
        private readonly object pageLoadedLock = new object();
    }
}